<?php
require('WoWArena5sParser.php');
require('BattlegroupList.php');

// cache update time
define('CACHE_UPDATE', 6*60); // in minutes

header('Content-type: text/html; charset=UTF-8');

$region = 'world';

// check if we want one region only
if (isset($_GET['region'])) {
	switch ($_GET['region']) {
		case 'us':
		case 'eu':
		case 'kr':
			define('CACHE', 'cache/arena_top50_5s_'.$_GET['region'].'.html');
			$region = $_GET['region']; // clean, because we've made sure, above.
			break;
		default:
			define('CACHE', 'cache/arena_top50_5s_world.html');
	}
} else {
	define('CACHE', 'cache/arena_top50_5s_world.html');
}

if (file_exists(CACHE) && (filemtime(CACHE) > (time()-(CACHE_UPDATE*60)))) { // exists & newer than XXmins?
	$page = file_get_contents(CACHE);
	echo $page;
	echo "<div id='cache_status'>This arena page is CACHED! It will be refreshed in ".ceil((filemtime(CACHE)-(time()-(CACHE_UPDATE*60)))/60)." minutes.</div>";
	echo "\t</body>\n";
	echo "</html>";
	exit;
}

// ok, no cache or out of date, recreate and then output.
touch(CACHE); // so only we rewrite the cache (hopefully)

function write_cache($buffer) {
	$fp = fopen(CACHE, 'w');
	if (!$fp) {
		return 1;
	}
	fwrite($fp, $buffer);
	fclose($fp);
}

$teams = array();
$ladder = new WoWCharacterParser();

// recreate the BG array if needed
if ($region == 'us') {
	$battlegroups = array('us' => $battlegroups['us']);
} else if ($region == 'eu') {
	$battlegroups = array('eu' => $battlegroups['eu']);
} else if ($region == 'kr') {
	$battlegroups = array('kr' => $battlegroups['kr']);
}

foreach ($battlegroups as $regioncode => $regiongroups) {
	foreach ($regiongroups as $battlegroup) {
		$ladder->loadArenaData($regioncode, $battlegroup);
		$ladder->parseXML();
		for ($i = 0; $i < 20; $i++) { // we know we're getting top 20
			$domain = ($regioncode == 'eu') ? 'http://armory.wow-europe.com/' : (($regioncode == 'kr') ? 'http://armory.worldofwarcraft.co.kr/' : 'http://armory.worldofwarcraft.com/');
			$teams[] = array(
				'Name'=> $ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/name'),
				'URL'=> $domain.'team-info.xml?t='.$ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/name').'&b='.$ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/battleGroup').'&ts=5&fl=1',
				'Region'=> $regioncode,
				'Battlegroup'=> $ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/battleGroup'),
				'Realm'=> $ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/realm'),
				'Faction'=> $ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/faction'),
				'Played'=> $ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/seasonGamesPlayed'),
				'Wins'=> $ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/seasonGamesWon'),
				'Rating'=> $ladder->getAttrib('page/arenaladderpagedresult/arenateams/arenateam['.$i.']/rating')
			);
		}
	}
}

function team_cmp($a, $b)
{
   if ($a['Rating'] == $b['Rating']) {
       return 0;
   }
   return ($a['Rating'] > $b['Rating']) ? -1 : 1;
}

// sort by rating
usort($teams, "team_cmp");
ob_start(); // begin output buffering
?>
<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
		<title>Thrissa's 5v5 Arena Leaderboard</title>
		<script type="text/javascript" src="http://siggen.xembler.org/js/prototype.js"></script>
		<script type="text/javascript">
			<!--			
				var sortType = 'Rank';
				var sortDir = -1; // 1 asc, -1 desc
				
				var arenaHeadings = Array();
				arenaHeadings['Rank'] = Array(0, 'num');
				arenaHeadings['Team Name'] = Array(1, 'str');
				arenaHeadings['Region'] = Array(2, 'str');
				arenaHeadings['Battlegroup'] = Array(3, 'str');
				arenaHeadings['Realm'] = Array(4, 'str');
				arenaHeadings['Faction'] = Array(5, 'str');
				arenaHeadings['Played'] = Array(6, 'num');
				arenaHeadings['Wins'] = Array(7, 'num');
				arenaHeadings['Losses'] = Array(8, 'num');
				arenaHeadings['Win%'] = Array(9, 'num');
				arenaHeadings['Rating'] = Array(10, 'num');
			
			<?php
				echo "var arenaData = Array(\n";
				$i = 0;
				$data = "";
				for ($i=0; $i < 50; $i++) {
					$data .= 'Array('.($i+1).', "<a href=\''.$teams[$i]['URL'].'\'>'.$teams[$i]['Name'].'</a>", "'.$teams[$i]['Region'].'", "'.$teams[$i]['Battlegroup'].'", "'.$teams[$i]['Realm'].'", "'.$teams[$i]['Faction'].'", '.$teams[$i]['Played'].', '.$teams[$i]['Wins'].', '.($teams[$i]['Played']-$teams[$i]['Wins']).', '.round(($teams[$i]['Wins']/$teams[$i]['Played'])*100,2).', '.$teams[$i]['Rating']."),\n";
				}
				echo substr($data, 0, count($data)-3)."\n"; // remove comma
				echo ");\n";
				
			?>
			
			function sortCompare(a, b) {
				var x = a[arenaHeadings[sortType][0]];
				var y = b[arenaHeadings[sortType][0]];
				
				if (arenaHeadings[sortType][1] == 'num') {
					return (sortDir<0) ? x - y : y - x;
				} else if (arenaHeadings[sortType][1] == 'str') {
					if (sortDir < 1) {
						return ((x < y) ? -1 : ((x > y) ? 1 : 0));
					} else {
						return ((x < y) ? 1 : ((x > y) ? -1 : 0));
					}
				}
				else return 0;
			}
			
			function displayBoard() {
				rows = document.getElementsByClassName('tdata');
				for (i = 0; i < rows.length; i++) {
					tdata = rows[i].getElementsByTagName('td');
					for (j = 0; j < tdata.length; j++) {
						tdata[j].innerHTML = arenaData[i][j];
					}
				}
			}
			
			function changeSort() {
				removeArrows(sortType);
				if (sortType == this.innerHTML) {
					// toggle sort dir
					sortDir = -sortDir;
				} else {
					sortDir = 1;
					sortType = this.innerHTML;
				}
				addArrows(this);
				arenaData.sort(sortCompare);
				displayBoard();
			}
			
			function removeArrows(oldA) {
				// remove oldA
				theads = $('thead').getElementsByTagName('th');
				for (i = 0; i < theads.length; i++) {
					if (theads[i].innerHTML.substring(0,oldA.length) == oldA) {
						theads[i].innerHTML = oldA;
					}
				}
			}
			
			function addArrows(newA) {				
				// add new
				if (sortDir<0) newA.innerHTML += '<span class="sort">\\/</span>';
				else newA.innerHTML += '<span class="sort">/\\</span>';
			}
			
			function Loaded() {
				// add hooks for sorting
				theads = $('thead').getElementsByTagName('th');
				for (i = 0; i < theads.length; i++) {
					theads[i].onclick = changeSort;
				}
			}
			
			//-->
		</script>
		<style type="text/css">
			#cache_status {
				background-color: #ccc;
				margin-top: 2em;
				text-align: center;
				padding: 2px;
			}
			th {
				background-color: #f66;
				padding: 5px;
				cursor: pointer;
			}
			tr {
				background-color: #fcc;
			}
			tr:hover {
				background-color: #f33;
			}
			td {
				padding: 2px;
			}
			td a {
				text-decoration: none;
			}
			html {
				font-family: verdana, arial, sans-serif;
			}
			.sort {
				font-size: 8px;
				padding-left: 1em;
			}
		</style>
	</head>
<body onload="Loaded();">
	<h1>Thrissa's 5v5 Arena Leaderboard</h1>
	<h2><?php echo strtoupper($region); ?> Top 50 5v5's</h2>
	<p>Hint: Click column headers for extra fun!</p>
	<p>Now available in all new RED: <a href="arena.php">World Top 50 5v5's</a> | <a href="arena.php?region=us">US Top 50 5v5's</a> | <a href="arena.php?region=eu">Europe Top 50 5v5's</a> | <a href="arena.php?region=kr">Korean Top 50 5v5's</a></p>
	<table>
		<tr id='thead'>
			<th>Rank<span class="sort">\/</span></th>
			<th>Team Name</th>
			<th>Region</th>
			<th>Battlegroup</th>
			<th>Realm</th>
			<th>Faction</th>
			<th>Played</th>
			<th>Wins</th>
			<th>Losses</th>
			<th>Win%</th>
			<th>Rating</th>
		</tr>
		<?php
		for ($i = 0; $i < 50; $i++) {
			echo "\t\t<tr class='tdata'>\n";
			echo "\t\t\t<td>".($i+1)."</td>\n";
			echo "\t\t\t<td><a href='".$teams[$i]['URL']."'>".$teams[$i]['Name']."</a></td>\n"; 
			echo "\t\t\t<td>".$teams[$i]['Region']."</td>\n";
			echo "\t\t\t<td>".$teams[$i]['Battlegroup']."</td>\n";
			echo "\t\t\t<td>".$teams[$i]['Realm']."</td>\n";
			echo "\t\t\t<td>".$teams[$i]['Faction']."</td>\n";
			echo "\t\t\t<td>".$teams[$i]['Played']."</td>\n";
			echo "\t\t\t<td>".$teams[$i]['Wins']."</td>\n";
			echo "\t\t\t<td>".($teams[$i]['Played']-$teams[$i]['Wins'])."</td>\n";
			echo "\t\t\t<td>".round(($teams[$i]['Wins']/$teams[$i]['Played'])*100,2)."</td>\n";
			echo "\t\t\t<td>".$teams[$i]['Rating']."</td>\n";
			echo "\t\t</tr>\n";
		}
		?>
	</table>
	<p>Brought to you by the maker of <a href='http://siggen.xembler.org'>siggen</a>, <a href='mailto:thrissa@gmail.com'>Thrissa</a> &lt;<a href='http://www.eminencewow.net/'>Eminence</a>&gt;</p>
<?php
write_cache(ob_get_contents());
?>
	<div id='cache_status'>This arena page was just generated, for YOU!</div>
	</body>
</html>